import * as L from 'leaflet'
import { WMTS } from './WMTS'
import { DomUtil } from 'leaflet/dist/leaflet-src.esm'
import icon from 'leaflet/dist/images/marker-icon.png'
import iconShadow from 'leaflet/dist/images/marker-shadow.png'
// import
const GeowayMap = function () {
    /**
     * 地图对象
     */
    this.geowayMap = null
    /**
     *获取地图对象
     **/
    this.getMap = () => this.geowayMap
    /**
     *编辑图层
     **/

    this.editLayer = null
    // 卷帘
    this.mapSplitControl = null
    /**
     *获取编辑图层
     */
    this.DRAWING = false // 是否正在绘制
    this.BarDRAWLAYERS = [] // 测距图层存储
    this.ISMEASURE = true // 是否是量距
    this.MEASURETOOLTIP=null // 量距提示
    this.DRAWMOVEPOLYLINE=null // 绘制过程中的折线
    this.DRAWPOLYLINEPOINTS = [] // 绘制的折线的节点集
    this.MEASURERESULT = 0
    this.DRAWMOVEPOLYGON=null // 绘制过程中的面
    this.DRAWPOLYGONPOINTS = [] // 绘制的面的节点集
    this.BarAreaLAYERS = []
    this.DRAWPOLYGON=null
    this.markerGroups = null // 聚合点存放
    this.getEditLayer = () => this.editLayer
    this.getContainer = function () {
        return this.geowayMap._container
    }
    // 测距
    this.startDrawLine = function (ISMEASURE) {
        let DRAWPOLYLINE = []
        const _this = this
        _this.ISMEASURE = ISMEASURE
        _this.getContainer().style.cursor = 'crosshair'
        _this.MEASURERESULT = 0
        // _this.geowayMap.getContainer().style.cursor = "crosshair";
        _this.geowayMap.on('mousedown', function (e) {
            _this.DRAWING = true
            _this.DRAWPOLYLINEPOINTS.push(e.latlng)
            if (_this.DRAWPOLYLINEPOINTS.length > 1 && _this.ISMEASURE) {
                _this.MEASURERESULT += e.latlng.distanceTo(
                    _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 2]
                )
            }
            DRAWPOLYLINE.addLatLng(e.latlng)
        })
        _this.geowayMap.on('mousemove', function (e) {
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYLINE != undefined &&
                    _this.DRAWMOVEPOLYLINE != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYLINE)
                }
                const prevPoint =
                    _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1]
                _this.DRAWMOVEPOLYLINE = new L.Polyline(
                    [prevPoint, e.latlng],
                    shapeOptions
                )
                _this.editLayer.addLayer(_this.DRAWMOVEPOLYLINE)

                if (ISMEASURE) {
                    const distance =
                        _this.MEASURERESULT +
                        e.latlng.distanceTo(
                            _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1]
                        )

                    _this.MEASURETOOLTIP.updatePosition(e.latlng)
                    _this.MEASURETOOLTIP.updateContent({
                        text: '单击确定点，双击结束！',
                        subtext: '总长：' + (distance / 1000).toFixed(2) + '公里'
                    })
                }
            }
        })

        _this.geowayMap.on('dblclick', function (e) {
            _this.getContainer().style.cursor = ''

            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYLINE != undefined &&
                    _this.DRAWMOVEPOLYLINE != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYLINE)
                    _this.DRAWMOVEPOLYLINE = null
                }

                if (_this.DRAWPOLYLINEPOINTS.length > 1 && ISMEASURE) {
                    _this.MEASURERESULT += e.latlng.distanceTo(
                        _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 2]
                    )

                    const distanceLabel = L.marker(
                        _this.DRAWPOLYLINEPOINTS[_this.DRAWPOLYLINEPOINTS.length - 1], {
                            icon: new L.divIcon({
                                className: 'DistanceLabelStyle',
                                iconAnchor: [-8, 15],
                                html: "<span class='bubbleLabel'><span class='bubbleLabel-bot bubbleLabel-bot-left'></span><span class='bubbleLabel-top bubbleLabel-top-left'></span><span>总长：" +
                                    (_this.MEASURERESULT / 1000).toFixed(2) +
                                    '公里' +
                                    '</span></span>'
                            })
                        }
                    ).addTo(_this.editLayer)

                    _this.BarDRAWLAYERS.push(distanceLabel)
                }

                // 移除提示框
                if (_this.MEASURETOOLTIP) {
                    _this.MEASURETOOLTIP.dispose()
                }
                _this.BarDRAWLAYERS.push(DRAWPOLYLINE)
                _this.DRAWPOLYLINEPOINTS = []
                _this.DRAWING = false
                _this.ISMEASURE = false
                _this.geowayMap.off('mousedown')
                _this.geowayMap.off('mousemove')
                _this.geowayMap.off('dblclick')
            }
        })
        const shapeOptions = {
            color: '#F54124',
            weight: 3,
            opacity: 0.8,
            fill: false,
            clickable: true
        }
        DRAWPOLYLINE = new L.Polyline([], shapeOptions)
        _this.editLayer.addLayer(DRAWPOLYLINE)
        if (_this.ISMEASURE) {
            _this.MEASURETOOLTIP = new L.Tooltip(_this.geowayMap)
        }
    }
    // 测面
    this.startDrawPolygon = function (ISMEASURE) {
        const _this = this
        _this.ISMEASURE = ISMEASURE
        _this.MEASURERESULT = 0
        _this.getContainer().style.cursor = 'crosshair'
        _this.geowayMap.on('mousedown', function (e) {
            _this.DRAWING = true
            _this.DRAWPOLYGONPOINTS.push(e.latlng)
            _this.DRAWPOLYGON.addLatLng(e.latlng)
        })
        _this.geowayMap.on('mousemove', function (e) {
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYGON != undefined &&
                    _this.DRAWMOVEPOLYGON != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYGON)
                }
                const prevPoint =
                    _this.DRAWPOLYGONPOINTS[_this.DRAWPOLYGONPOINTS.length - 1]
                const firstPoint = _this.DRAWPOLYGONPOINTS[0]
                _this.DRAWMOVEPOLYGON = new L.Polygon(
                    [firstPoint, prevPoint, e.latlng],
                    shapeOptions
                )
                _this.editLayer.addLayer(_this.DRAWMOVEPOLYGON)

                if (_this.ISMEASURE && _this.DRAWPOLYGONPOINTS.length > 1) {
                    const tempPoints = []
                    for (let i = 0; i < _this.DRAWPOLYGONPOINTS.length; i++) {
                        tempPoints.push(_this.DRAWPOLYGONPOINTS[i])
                    }
                    tempPoints.push(e.latlng)
                    const distance = _this.calArea(tempPoints)
                    _this.MEASUREAREATOOLTIP.updatePosition(e.latlng)
                    _this.MEASUREAREATOOLTIP.updateContent({
                        text: '单击确定点，双击结束！',
                        subtext: '总面积：' + (distance / 1000000).toFixed(3) + '平方公里'
                    })
                }
            }
        })

        _this.geowayMap.on('dblclick', function (e) {
            _this.getContainer().style.cursor = ''
            if (_this.DRAWING) {
                if (
                    _this.DRAWMOVEPOLYGON != undefined &&
                    _this.DRAWMOVEPOLYGON != null
                ) {
                    _this.editLayer.removeLayer(_this.DRAWMOVEPOLYGON)
                    _this.DRAWMOVEPOLYGON = null
                }

                if (_this.DRAWPOLYGONPOINTS.length > 2 && _this.ISMEASURE) {
                    _this.MEASURERESULT = _this.calArea(_this.DRAWPOLYGONPOINTS)

                    const distanceLabel = L.marker(e.latlng, {
                        icon: new L.divIcon({
                            className: 'DistanceLabelStyle',
                            iconAnchor: [-8, 15],
                            html: "<span class='bubbleLabel'><span class='bubbleLabel-bot bubbleLabel-bot-left'></span><span class='bubbleLabel-top bubbleLabel-top-left'></span><span>总面积：" +
                                (_this.MEASURERESULT / 1000000).toFixed(3) +
                                '平方公里' +
                                '</span></span>'
                        })
                    }).addTo(_this.editLayer)

                    _this.BarDRAWLAYERS.push(distanceLabel)
                }

                // 移除提示框
                if (_this.MEASUREAREATOOLTIP) {
                    _this.MEASUREAREATOOLTIP.dispose()
                }

                _this.BarDRAWLAYERS.push(_this.DRAWPOLYGON)
                _this.DRAWPOLYGONPOINTS = []
                _this.DRAWING = false
                _this.ISMEASURE = false
                _this.geowayMap.off('mousedown')
                _this.geowayMap.off('mousemove')
                _this.geowayMap.off('dblclick')
            }
        })

        const shapeOptions = {
            color: '#F54124',
            weight: 3,
            opacity: 0.8,
            fill: true,
            fillColor: null,
            fillOpacity: 0.2,
            clickable: true
        }
        _this.DRAWPOLYGON = new L.polygon([], shapeOptions)
        _this.editLayer.addLayer(_this.DRAWPOLYGON)
        if (_this.ISMEASURE) {
            _this.MEASUREAREATOOLTIP = new L.Tooltip(_this.editLayer)
        }
    }
    // 面积计算
    this.calArea = function (latLngs) {
        const pointsCount = latLngs.length
            let area = 0.0
            const d2r = Math.PI / 180
            let p1
            let p2
        if (pointsCount > 2) {
            for (let i = 0; i < pointsCount; i++) {
                p1 = latLngs[i]
                p2 = latLngs[(i + 1) % pointsCount]
                area +=
                    (p2.lng - p1.lng) *
                    d2r *
                    (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r))
            }
            area = (area * 6378137.0 * 6378137.0) / 2.0
        }
        return Math.abs(area)
    }
    // 清除测面、测距
    this.clearMap = function () {
        const _this = this
        // 关闭测距提示框
        if (_this.MEASURETOOLTIP) {
            _this.MEASURETOOLTIP.dispose()
        }
        // 关闭测面提示框
        if (_this.MEASUREAREATOOLTIP) {
            _this.MEASUREAREATOOLTIP.dispose()
        }

        // array exists and is not empty
        if (_this.BarDRAWLAYERS.length > 0) {
            for (let i = 0; i < _this.BarDRAWLAYERS.length; i++) {
                _this.geowayMap.removeLayer(_this.BarDRAWLAYERS[i])
            }
            _this.BarDRAWLAYERS = []
        }
        // 清除聚合点
        if (_this.markerGroups) {
            _this.markerGroups.clearLayers()
        }
    }
    /**
     * 初始化地图
     */
    this.initMap = function (mapdiv, cfg) {
        this.mapLayer = null
        this.editLayer = null
        this.geowayMap = null
        this.geowayMap = L.map(mapdiv, {
            crs: cfg.mapInfo.crs,
            zoomControl: false,
            center: cfg.mapInfo.center,
            zoom: cfg.mapInfo.level,
            minZoom: cfg.mapInfo.minlevel,
            maxZoom: cfg.mapInfo.maxlevel,
            doubleClickZoom: false
        })
        this.initMapLayer()
        this.initManagerLayer()
        this.Switchmap()
    }
    /**
     *添加辅助图层管理
     */
    this.initManagerLayer = function () {
        // 编辑图层
        this.editLayer = L.featureGroup()
        this.geowayMap.addLayer(this.editLayer)
    }
    /**
     *添加底图图层管理
     */
    this.initMapLayer = function () {
        // 编辑图层
        this.mapLayer = L.featureGroup()
        this.geowayMap.addLayer(this.mapLayer)
    }
    /**
     *初始化地图控件
     *map 地图对象
     *config 控件显示配置
     **/
    this.initBaseControls = config => {
        if (typeof config === 'undefined') config = {}
        // 加载比例尺
        if (!config.hasOwnProperty('IsScale') || config.IsScale == true) {
            L.control.scale().addTo(this.geowayMap)
            L.control
                .zoom({
                    zoomInTitle: '放大',
                    zoomOutTitle: '缩小',
                    position: 'topright'
                })
                .addTo(this.geowayMap)
            L.control.mousePosition().addTo(this.geowayMap)
        }
    }
    /**
     *初始化图层
     *@param layers添加图层数组
     *@param config图层配置信息
     */
    this.addMapLayers = (layers, config) => {
        if (typeof config === 'undefined') layers = []
        for (let count = 0; count < layers.length; count++) {
            const layerinfo = layers[count]
            if (layerinfo.serviceType === 'wmts') {
                this.addMapLayer(layerinfo)
            } else {
                L.tileLayer(layerinfo.url, {
                    tileSize: 256,
                    zoomOffset: 1,
                    attribution: layerinfo.attribution,
                    isBaseLayer: layerinfo.isBaseLayer,
                    subdomains: layerinfo.subdomains
                }).addTo(this.geowayMap)
            }
        }
    }
    /**
     * 添加图层信息
     * @param layerinfo图层信息
     */
    this.addMapLayer = function (layerinfo) {
        let layer = null
        const visibility =
            typeof layerinfo.visibility === 'undefined' ? true : layerinfo.visibility
        const isBaseLayer =
            typeof layerinfo.isBaseLayer === 'undefined'
            ? false
            : layerinfo.isBaseLayer
        switch (layerinfo.serviceType) {
            case 'wmts':
                const style = 'default'
                const format =
                    typeof layerinfo.format === 'undefined'
                    ? 'image/png'
                    : layerinfo.format
                let layerleName
                const tilematrixSet =
                    typeof layerinfo.tilematrixSet === 'undefined'
                    ? ''
                    : layerinfo.tilematrixSet
                const matrixIds = []
                for (let i = 0; i < 15; ++i) {
                    matrixIds[i] = {
                        identifier: '' + (i + 1),
                        topLeftCorner: new L.LatLng(90, -180)
                    }
                }
                layer = new L.TileLayer.WMTS(layerinfo.url, {
                    layer: layerinfo.layer,
                    style: '',
                    tilematrixSet: tilematrixSet,
                    format: format,
                    matrixIds: matrixIds,
                    attribution: layerinfo.attribution
                })
                break
        }
        if (layer != null) {
            this.geowayMap.addLayer(layer)
        }

        return layer
    }
    /**
     * 清除地图上所有图层
     */
    this.removeDrawLayer = () => {
        this.editLayer.clearLayers()
        if (this.mapSplitControl) {
            this.mapSplitControl.remove()
            this.mapSplitControl = null
        }
    }
    /**
     * 清除地图底图所有图层
     */
    this.removeMapLayer = () => {
        this.mapLayer.clearLayers()
    }
    /**
     * 全幅
     */
    this.fullMap = () => {
        this.geowayMap.setView([37, 102], 3)
    }

    /**
     * 放大按钮
     */
    this.zoomOut = () => {
        this.geowayMap.zoomOut()
    }

    /**
     * 缩小按钮
     */
    this.zoomIn = () => {
        this.geowayMap.zoomIn()
    }
    /**
     * 绘制矩形
     */
    this.drawRectangle = (fn) => {
        // debugger;
        this.editLayer.clearLayers()
        let rectangle
        let tmprec
        const latlngs = []
        this.geowayMap.dragging.disable()
        this.geowayMap.on('mousedown', e => {
            if (typeof tmprec !== 'undefined') {
                tmprec.remove()
            }
            // 左上角坐标
            latlngs[0] = e.latlng
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on('mousemove', e => {
                this.editLayer.clearLayers()
                latlngs[1] = e.latlng
                // 删除临时矩形
                if (typeof tmprect !== 'undefined') {
                    tmprec.remove()
                }
                // 添加临时矩形
                tmprec = L.rectangle(latlngs, this.drawStyleMap.Polygon).addTo(
                    this.editLayer
                )
            })
        })
        this.geowayMap.on('mouseup', e => {
            this.editLayer.clearLayers()
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off('mousedown')
            this.geowayMap.off('mousemove')
            this.geowayMap.off('mouseup')
            // 右下角坐标
            latlngs[1] = e.latlng
            rectangle = L.rectangle(latlngs, this.drawStyleMap.Polygon)
            const result = []
            result.push(latlngs)
            rectangle.addTo(this.editLayer)
            this.geowayMap.dragging.enable()
            if (fn) {
                // 如果需要获取到当前坐标  使用当前回调
                fn(rectangle)
            }
        })
    }
    /**
     * 绘制多边形
     */
    this.drawPolygon = function (fn) {
        this.editLayer.clearLayers()
        const points = []
        const polygon = new L.polygon(points)
        this.geowayMap.addLayer(polygon)
        this.geowayMap.on('mousedown', e => {
            points.push([e.latlng.lat, e.latlng.lng])

            this.geowayMap.on('mousemove', event => {
                polygon.setLatLngs([...points, [event.latlng.lat, event.latlng.lng]])
            })
        })
        this.geowayMap.on('dblclick', () => {
            if (points.length) {
                this.geowayMap.off('mousedown')
                this.geowayMap.off('mousemove')
                this.geowayMap.off('dblclick')
                polygon.addTo(this.editLayer)
                if (fn) {
                    fn(polygon)
                }
            }
        })
    }

    /**
     * 绘制线
     */
    this.drawPolyline = () => {
        this.editLayer.clearLayers()
        let rectangle
        let tmprec
        const latlngs = []
        this.geowayMap.dragging.disable()
        this.geowayMap.on('mousedown', e => {
            if (typeof tmprec !== 'undefined') {
                tmprec.remove()
            }
            // 左上角坐标
            latlngs[0] = e.latlng
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on('mousemove', e => {
                this.editLayer.clearLayers()
                latlngs[1] = e.latlng
                // 删除临时矩形
                if (typeof tmprect !== 'undefined') {
                    tmprec.remove()
                }
                // 添加临时矩形
                tmprec = L.polyline(latlngs, this.drawStyleMap.Line).addTo(
                    this.editLayer
                )
            })
        })
        this.geowayMap.on('mouseup', e => {
            this.editLayer.clearLayers()
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off('mousedown')
            this.geowayMap.off('mousemove')
            this.geowayMap.off('mouseup')
            // 右下角坐标
            latlngs[1] = e.latlng
            rectangle = L.polyline(latlngs, this.drawStyleMap.Line)
            const result = []
            result.push(latlngs)
            rectangle.addTo(this.editLayer)
            this.geowayMap.dragging.enable()
        })
    }
    /**
     * 绘制点
     */
    this.drawPoint = () => {
        this.editLayer.clearLayers()
        let rectangle
        let tmprec
        const latlngs = []
        this.geowayMap.dragging.disable()
        this.geowayMap.on('mousedown', e => {
            if (typeof tmprec !== 'undefined') {
                tmprec.remove()
            }
            // 左上角坐标
            latlngs[0] = e.latlng.lat
            latlngs[1] = e.latlng.lng
            // 开始绘制，监听鼠标移动事件
            this.geowayMap.on('mousemove', e => {
                this.editLayer.clearLayers()
                // 删除临时矩形
                if (typeof tmprect !== 'undefined') {
                    tmprec.remove()
                }
                // 添加临时矩形
                tmprec = L.circle(
                    latlngs, {
                        radius: 1
                    },
                    this.drawStyleMap.Line
                ).addTo(this.editLayer)
            })
        })
        this.geowayMap.on('mouseup', e => {
            this.editLayer.clearLayers()
            // 矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
            this.geowayMap.off('mousedown')
            this.geowayMap.off('mousemove')
            this.geowayMap.off('mouseup')
            rectangle = L.circle(
                latlngs, {
                    radius: 1
                },
                this.drawStyleMap.Line
            )
            const result = []
            result.push(latlngs)
            rectangle.addTo(this.editLayer)
            this.geowayMap.dragging.enable()
        })
    }
    this.imageOption = {
        skyMap1: WMTS(
            'http://t0.tianditu.gov.cn/vec_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'vec',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        ),
        skyMap2: WMTS(
            'http://t0.tianditu.gov.cn/cva_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'cva',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        ),
        // 天地图之地形的配置
        skymapTopography1: WMTS(
            'http://t0.tianditu.gov.cn/ter_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'ter',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        ),
        skymapTopography2: WMTS(
            'http://t0.tianditu.gov.cn/cta_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'cta',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        ),
        // 天地图之影像的配置
        skymapImage1: WMTS(
            'http://t0.tianditu.gov.cn/img_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'img',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        ),
        skymapImage2: WMTS(
            'http://t0.tianditu.gov.cn/cia_c/wmts?tk=5f62055ba4a942589b724283706c399a', {
                layer: 'cia',
                tileMatrixSet: 'c',
                format: 'tiles',
                style: 'default',
                type: 'baseLayer'
            }
        )

    }
    /**
     *全局绘制样式配置
     **/
    this.drawStyleMap = {
        Point: {
            pointRadius: 5,
            graphicName: 'circle',
            fillColor: 'white',
            fillOpacity: 1,
            strokeWidth: 1,
            strokeOpacity: 1,
            strokeColor: '#ed7540',
            strokeLinecap: 'round'
        },
        Line: {
            strokeWidth: 3,
            strokeOpacity: 1,
            strokeColor: '#ed7540',
            strokeDashstyle: 'longdash',
            strokeLinecap: 'butt'
        },
        Polygon: {
            color: '#3388FF',
            fillOpacity: 0.1,
            weight: 2
        }

    }

    this.initHightPoly = function (coordinates, style, isView, type, pane) {
        if (type == undefined || type == null) {
            type = 'Polygon'
        }
        if (pane === null || pane === '' || pane == undefined) {
            pane = 'overlayPane'
        }
        const geoJsonLayer = L.geoJson(coordinates, {
            style: style,
            pane: pane
        }).addTo(this.editLayer)
        if (isView) {
            const latling = geoJsonLayer.getBounds().getCenter()
            const center = L.latLng(latling.lat, latling.lng)
            const currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()) // 缩放比例
            this.getMap().setView(center, currentZoom)
        }
        return geoJsonLayer
    }
    this.initHightPolyMap = function (coordinates, style, isView, type, pane) {
        if (type == undefined || type == null) {
            type = 'Polygon'
        }
        if (pane === null || pane === '' || pane == undefined) {
            pane = 'overlayPane'
        }
        const geoJsonLayer = L.geoJson(coordinates, {
            style: style,
            pane: pane
        }).addTo(this.geowayMap)
        if (isView) {
            const latling = geoJsonLayer.getBounds().getCenter()
            const center = L.latLng(latling.lat, latling.lng)
            const currentZoom = this.getMap().getBoundsZoom(geoJsonLayer.getBounds()) // 缩放比例
            this.getMap().setView(center, currentZoom)
        }
        return geoJsonLayer
    }

    this.addAPolygon = function (geometry) {
        this.editLayer.clearLayers()
        const polygon = geometry.coordinates
        const polygon1 = []
        for (const item in polygon) {
            const cor = polygon[item]
            const cor1 = []
            cor1[0] = cor[1]
            cor1[1] = cor[0]
            polygon1.push(cor1)
        }
        const polygon2 = L.polygon(polygon1, {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.2
        })
        polygon2.addTo(this.editLayer)
    }

    // 地图切换
    this.Switchmap = function () {
        this.removeMapLayer()
        this.mapLayer.addLayer(this.imageOption.skyMap1)
        this.mapLayer.addLayer(this.imageOption.skyMap2)
    }
    // 切换成地形
    this.TerrainSwitching = function () {
        this.removeMapLayer()
        this.mapLayer.addLayer(this.imageOption.skymapTopography1)
        this.mapLayer.addLayer(this.imageOption.skymapTopography2)
    }
    // 影像切换
    this.SwitchingImages = function () {
        this.removeMapLayer()
        this.mapLayer.addLayer(this.imageOption.skymapImage1)
        this.mapLayer.addLayer(this.imageOption.skymapImage2)
    }

    // 卷帘效果 skymapImage1 skymapImage2底图
    this.sideBySide = function (status) {
        if (this.mapSplitControl) {
            this.mapSplitControl.remove()
            this.mapSplitControl = null
        } else {
            const this_ = this
            const osmLayer = this.imageOption.skymapImage1.addTo(this_.geowayMap)
            const stamenLayer = this.imageOption.skymapImage2.addTo(this_.geowayMap)
            this_.mapSplitControl = L.control.sideBySide(osmLayer, stamenLayer)
            this_.mapSplitControl.addTo(this_.geowayMap)
        }
    }
    // 删除指定图层 removeLayer(marker)
    this.removeLayer = function (layer) {
        this.editLayer.removeLayer(layer)
        // this.geowayMap.removeLayer(layer)
    }
    // 图片叠加
    this.imageOverlay = function (img, point1, point2, point3, isView) {
        const imageLayer = L.imageOverlay
            .rotated(img, point1, point2, point3, {
                opacity: 1,
                interactive: true
                // attribution: ""
            })
            .addTo(this.editLayer)
        const bounds = new L.LatLngBounds(point1, point2).extend(point3)
        if (isView) {
            this.getMap().fitBounds(bounds)
        }

        return imageLayer
    }
    this.getRandomLatLng = function (num) {
        var bounds = num.getBounds()
            // 获取左下角坐标
            var southWest = bounds.getSouthWest()
            // 获取右下角坐标
            var northEast = bounds.getNorthEast()
            // 获取地图范围的长
            var lngSpan = northEast.lng - southWest.lng
            // 获取地图范围的宽
            var latSpan = northEast.lat - southWest.lat
        return L.latLng(
            // 返回任意地图范围内的x坐标
            southWest.lat + latSpan * Math.random(),
            // 返回任意地图范围内的y坐标
            southWest.lng + lngSpan * Math.random())
    }
    // 加载GeoJSON
    this.showGeoJSON = function () {
        const someFeatures = [{
                'type': 'Feature',
                'properties': { 'party': 'Republican', 'name': '三角形' },
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [
                        [
                            [116.3, 40],
                            [116.37, 40],
                            [116.34, 40.05]
                        ]
                    ]
                }
            },
            {
                'type': 'Feature',
                'properties': { 'party': 'Democrat', 'name': '矩形' },
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [
                        [
                            [116.22, 40],
                            [116.26, 40],
                            [116.26, 40.05],
                            [116.22, 40.05]

                        ]
                    ]
                }
            }
        ]
        const layGeo = L.geoJson(someFeatures, {
            style: {
                'color': '#00f',
                'weight': 3,
                'opacity': 0.5

            }
        })
        layGeo.addTo(this.geowayMap)
    }
}
export default GeowayMap
